<?php

/**
 * 检测并且创建目录
 * @param $directory
 * @return bool
 */
function checkAndCreateDirectory($directory)
{
    if (empty($directory)) {
        return false;
    }

    if (!is_dir($directory)) {
        if (!mkdir($directory, 0755, true)) {
            return false;
        }
    }
    return true;
}


/**
 * @param $message
 */
function dump($message)
{
    fwrite(STDOUT, $message);
    die();
}

/**
 * 连接数据库，优先从env路径中获取
 * @return mysqli
 */
function db()
{

    $envVariable = [];
    $envFile = preg_replace('/tools/', '.env', TOOLS_ENTRANCE);
    if (is_file($envFile)) {
        $envVariable = parse_ini_file($envFile, true);
    }

    if ($envVariable) {
        $database = $envVariable['database'];
        $database['port']=$database['hostport'];
    } else {
        $database = config('database');
    }

    $connect = mysqli_connect(
        $database['hostname'],
        $database['username'],
        $database['password'],
        $database['database'],
        $database['port']
    ) or die('数据库连接失败,请检查Config.ini中的database信息');

    mysqli_query($connect, 'set names ' . $database['charset']);
    return $connect;
}

/**
 * @param $table_name
 * @return array
 */
function tableColumns($table_name)
{
    $bale_name_type = config('database.table_name_type');
    if ($bale_name_type == 1) {
        $table_name = transToUnderline($table_name);
    } elseif ($bale_name_type == 2) {
        $table_name = transToCamelCase($table_name);
    } else {
        $table_name = transToPascal($table_name);
    }

    $sql = 'show full columns from `' . $table_name . '`';
    $resource = db()->query($sql);

    if (empty($resource)) {
        die('没有查询到 ' . $table_name . ' 的表信息(下划线方式)');
    }

    $result = [];
    while ($item = $resource->fetch_assoc()) {
        $result[] = $item;
    }

    return $result;
}

/**
 * 驼峰转命名(含帕卡斯)转化为下划线命名
 * @param string $variable
 * @return mixed|string
 */
function transToUnderline(string $variable)
{
    if (empty($variable)) {
        return $variable;
    }
    $variable = trim($variable, '_');
    $variable = preg_replace_callback('/([A-Z])/', function ($matches) {
        return '_' . lcfirst(isset($matches[1]) ? $matches[1] : '');
    }, $variable);
    return trim($variable, '_');
}

/**
 * 下划线命名(含驼峰)转化为帕斯卡命名法（驼峰命名法的首字母大写）
 * @param string $variable
 * @return mixed|string
 */
function transToPascal(string $variable = '')
{
    if (empty($variable)) {
        return $variable;
    }
    $variable = trim($variable, '_');
    $variable = preg_replace_callback('/_([a-z])/', function ($matches) {
        return ucfirst(isset($matches[1]) ? $matches[1] : '');
    }, $variable);
    return ucfirst($variable);
}

/**
 * 字符串转化为驼峰命名法
 * @param string $variable
 * @return null|string|string[]
 */
function transToCamelCase(string $variable = '')
{
    if (empty($variable)) {
        return $variable;
    }
    $variable = trim($variable, '_');
    $variable = preg_replace_callback('/_([a-z])/', function ($matches) {
        return ucfirst(isset($matches[1]) ? $matches[1] : '');
    }, $variable);

    return lcfirst($variable);
}


/**
 * 检测字段是否满足配置常亮的条件
 * @param array $field_info
 * @return bool
 */
function isSatisfyConstant($field_info)
{
    $field = isset($field_info['Field']) ? $field_info['Field'] : '';
    $type = isset($field_info['Type']) ? $field_info['Type'] : '';

    if ($field == 'sort') {
        return false;
    }

    if (
        preg_match('/tinyint/', $type)
        ||
        $field == 'status'
        ||
        $field == 'type'
    ) {
        return true;
    }

    return false;
}

/**
 * 把数据拼接成可阅读的数组形式
 * @param array $params
 * @param string $prefix
 * @return string
 */
function concatArrayFormatNoKey($params, $prefix = '        ')
{
    $fields = '';
    foreach ($params as $item) {
        $fields .= $prefix
            . '\''
            . $item
            . "',\n";
    }

    $fields = '['
        . "\n"
        . $fields
        . '    ]';

    return $fields;
}

/**
 * 拼接成带键的数组形式
 * @param array $params 参数
 * @param string $prefix 前缀空格
 * @return string
 */
function concatArrayFormat($params, $prefix = '        ')
{
    $template = '';
    foreach ($params as $key => $item) {
        $template .= $prefix
            . '\'' . $key . '\''
            . ' => \'' . $item . '\''
            . ','
            . "\n";
    }

    $template = '['
        . "\n"
        . $template
        . '    ]';

    return $template;
}

/**
 *
 * 解析既定的字典描述信息
 *
 * 正确解析:
 *  状态  0 不展示 hide 1 展示 show
 *
 * 不解析:
 *  年龄
 *
 * @param array|string $comment 字段的评论信息，
 * @param bool $chunk 去掉第一个数据，通常作为描述信息使用
 * @return array
 */
function parseFieldComment($comment, $chunk = true)
{
    if (is_array($comment)) {
        $comment = isset($comment['Comment']) ? $comment['Comment'] : '';
    }

    if (empty($comment)) {
        return [];
    }

    $field_comment = explode(' ', $comment);

    /**
     * 过滤空置(注意0值)
     */
    $field_comment = array_filter($field_comment, function ($value) {
        if ($value === '') {
            return false;
        }
        return true;
    });

    if ($chunk) {
        array_shift($field_comment);
        $field_comment = array_chunk($field_comment, 3);
    }

    return $field_comment;
}

/**
 * 把数据库中的字段追加为模型的属性
 * @param $property
 * @param $name
 * @param $namespace
 * @return string
 */
function appendModelClassProperty($property, $name, $namespace)
{
    $name = preg_replace('/[^\w]/', '', $name);

    $namespace = preg_replace(['/namespace/', '/[^\w\\\]/'], ['', ''], $namespace);

    $result = <<<EOF
/**
 * Class $name
 * @package $namespace
EOF;

    $result .= "\n";

    if ($property) {
        foreach ($property as $item) {
            if (preg_match('/int/', $item['type'])) {
                $type = 'integer';
            } elseif (preg_match('/decimal/', $item['type'])) {
                $type = 'float';
            } else {
                $type = 'string';
            }
            $result .= " * @property $type $" . $item['field'] . "\n";
        }
    }

    return $result . ' */';
}